package com.yl.chainStore.services.impl.pay

import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.payrule.common.DiscountComputeOrderResultVo
import com.yl.chainStore.payrule.order.OrderRuleService
import com.yl.chainStore.services.pay.IOrderRuleService
import com.yl.chainStore.services.pay.ISysCompanyPayItemService
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class OrderRuleServiceImpl(): IOrderRuleService {

	companion object {
		private val log = LoggerFactory.getLogger(IOrderRuleService::class.java)
	}
	@Autowired
	private lateinit var orderRuleService:List<OrderRuleService>

	@Autowired
	private lateinit var iSysCompanyPayItemService:ISysCompanyPayItemService

	override fun completeOrder(order: PayCustomerOrder): DiscountComputeOrderResultVo {
		log.info("订单优惠管理：==>: 执行订单：order:{}",order)

		verifyOrder(order)
		var resOrder = order
		for(rules in orderRuleService){
			val computeOrder = rules.computeOrder(order)
			resOrder = computeOrder.order
		}
		return DiscountComputeOrderResultVo(returnSuccess(),resOrder)
	}

	/**
	 * 核算之前要处理的数据
	 */
	private fun verifyOrder(order: PayCustomerOrder): ResponseBody {
		if (order.details != null) {
			for (detail in order.details!!) {
				if(detail.typeId == null || detail.typeId == 0L){
					val deptItemDetail = iSysCompanyPayItemService.itemDetail(detail.itemId, getContext().subCompanyId)
					if(deptItemDetail != null ){
						detail.typeId = deptItemDetail.typeId
					}
				}
			}
		}
		return returnSuccess()
	}
}
